/**
 * 
 */
package la.ge.server.servlets.repository.viewer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import la.common.CommonException;
import la.common.xml.NamespaceContextMap;
import la.common.xml.NamespaceCorrector;
import la.common.xml.Node2String;
import la.common.xml.XMLHelper;
import la.ge.common.CoordinateUtil;
import la.ge.common.Point;
import la.ge.common.Rect;
import la.ge.kml.KMLConstants;
import la.ge.kml.KMLHelper;
import la.ge.server.GeServerContext;
import la.ge.server.common.ServerUtil;
import la.ge.server.servlets.gs2ge.util.Util;

import org.apache.commons.io.IOUtils;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import com.google.earth.kml.x20.KmlDocument;
import com.google.earth.kml.x20.KmlDocument.Kml;
import com.google.earth.kml.x20.NetworkLinkDocument.NetworkLink;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

public class ViewerServlet extends HttpServlet
{
	public ViewerServlet() {
		Element e;
//		e.
	}
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
    	GeServerContext geServerContext = (GeServerContext) this.getServletContext().getAttribute( GeServerContext.ATTRIB_NAME );
		response.setContentType( KMLConstants.KML_MIME );
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println(
					gen( 
					Util.genClientAccessURLPrefix(request) +
					geServerContext.getServletPath( RespositoryViewerServlet.class )));
		} catch ( CommonException e ) {
			InputStream failKMLIS = RespositoryViewerServlet.class
					.getResourceAsStream("/la/ge/kml/error_template.kml.xml");
			IOUtils.copy(failKMLIS, response.getOutputStream());
			failKMLIS.close();
		}
    }
    
    /**
     * 
     * @param respositoryViewerURL
     * @return format: http://localhost:8080/la.ge.server.viewer.RespositoryViewerServlet
     * @throws CommonException
     */
	public static String gen(String respositoryViewerURL) throws CommonException {
		try {
			DocumentBuilder db = XMLHelper.instance.getDocBuilder();
			
			XPath xpath = XPathFactory.newInstance().newXPath();
			xpath.setNamespaceContext( KMLHelper.KML20XMLNSContext );

			Element eDocument = null;
			{
				XPathExpression expr = xpath.compile( "/kml:kml/kml:Document" );
				String uri = ViewerServlet.class.getResource( "/la/ge/server/viewer/kml.xml" ).toString();
				Document doc = db.parse( uri );
				eDocument = (Element) expr.evaluate( doc, XPathConstants.NODE );
			}
			
			Element eNetworkTemplate = null;
			{
				String uri = ViewerServlet.class.getResource(
						"/la/ge/server/viewer/viewer.xml").toString();
				Document doc2 = db.parse(uri);
				eNetworkTemplate = doc2.getDocumentElement();
				eNetworkTemplate = (Element) eDocument.getOwnerDocument().importNode(eNetworkTemplate, true);
			}

			File respositoryHome = new File("./repository/");
			XPathExpression expr = xpath.compile( "kml:Url/kml:href" );
			for(File file : respositoryHome.listFiles()) {
				Element fileNetLink =  (Element) eNetworkTemplate.cloneNode( true );
				((Element) xpath.compile("kml:name").evaluate(fileNetLink,
						XPathConstants.NODE)).setTextContent(file.getName());

				Element eHref = (Element) expr.evaluate( fileNetLink, XPathConstants.NODE );
				eHref.setTextContent( respositoryViewerURL + "?file=" + file.getName() );

				eDocument.appendChild( fileNetLink );
			}
			String result = Node2String.node2String( eDocument.getOwnerDocument() );
			System.out.println( result );
			return result;
		} catch ( Exception e ) {
			throw new CommonException( e );
		}
	}
	
	


}